import 'dart:math' show Random;

import 'package:flutter/material.dart';

class SliverWidget extends StatefulWidget {
  const SliverWidget({super.key});

  @override
  State<StatefulWidget> createState() {
    return _SliverWidget();
  }
}

class _SliverWidget extends State<SliverWidget> with TickerProviderStateMixin {
  Color getRandomColor({int r = 255, int g = 255, int b = 255, a = 255}) {
    if (r == 0 || g == 0 || b == 0) return Colors.black;
    if (a == 0) return Colors.white;
    return Color.fromARGB(
      a,
      r != 255 ? r : Random.secure().nextInt(r),
      g != 255 ? g : Random.secure().nextInt(g),
      b != 255 ? b : Random.secure().nextInt(b),
    );
  }

  late TabController tabController;

  @override
  Widget build(BuildContext context) {
    tabController = TabController(length: 2, vsync: this);
    return Scaffold(
      body: CustomScrollView(
        slivers: [
          SliverAppBar(
            //是否向下滑动时立即显示appBar
            floating: true,
            //appBar是否固定到顶部
            pinned: true,
            snap: true,
            //是否显示在状态栏的下面,false就会占领状态栏的高度
            primary: true,
            expandedHeight: 200,
            title: const Text(
              "Sliver用法",
              style: TextStyle(fontWeight: FontWeight.bold, fontSize: 12),
            ),
            backgroundColor: Colors.blue,
            flexibleSpace: FlexibleSpaceBar(
              centerTitle: true,
              title: const Text(
                "我是Sliver",
                style: TextStyle(fontWeight: FontWeight.bold, fontSize: 12),
              ),
              background: Image.asset(
                'images/banner_image1.png',
                fit: BoxFit.cover,
              ),
            ),
          ),
          SliverPersistentHeader(
            pinned: true,
            delegate: _SliverPersistentHeaderDelegateFloating(),
          ),
          SliverPersistentHeader(
            pinned: true,
            delegate: _SliverPersistentHeaderDelegate(
              TabBar(
                labelColor: Colors.red,
                unselectedLabelColor: Colors.grey,
                tabs: const [
                  Tab(icon: Icon(Icons.cake), text: '左侧'),
                  Tab(icon: Icon(Icons.golf_course), text: '右侧'),
                ],
                controller: tabController,
              ),
            ),
          ),
          SliverFillRemaining(
            // 剩余补充内容TabBarView
            child: TabBarView(
              controller: tabController,
              children: const [
                Center(child: Text('Content of Home')),
                Center(child: Text('Content of Profile')),
              ],
            ),
          ),
          SliverList(
            delegate: SliverChildListDelegate([
              Container(
                color: getRandomColor(),
                height: 50,
              ),
              Container(
                color: getRandomColor(),
                height: 50,
              ),
              Container(
                color: getRandomColor(),
                height: 50,
              ),
            ]),
          ),
          SliverList(
            delegate: SliverChildBuilderDelegate(
              (context, index) => Container(
                color: getRandomColor(),
                height: 30,
              ),
              childCount: 5,
            ),
          ),
          SliverGrid(
            delegate: SliverChildBuilderDelegate(
              (context, index) => Container(
                color: Colors.blueGrey,
                padding: const EdgeInsets.all(10),
                child: Card(
                  color: getRandomColor(),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: Container(),
                ),
              ),
              childCount: 25 + 3,
            ),
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 4,
              mainAxisSpacing: 0,
              crossAxisSpacing: 0,
              mainAxisExtent: 50,
            ),
          ),
          // SliverPadding(
          //   padding: const EdgeInsets.all(10),
          //
          // ),
        ],
      ),
    );
  }
}

class _SliverPersistentHeaderDelegateFloating
    extends SliverPersistentHeaderDelegate {
  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return Container(
      color: Colors.green,
      child: Stack(
        children: [
          Image.asset(
            'images/banner_image2.png',
            width: MediaQuery.of(context).size.width,
            fit: BoxFit.cover,
          ),
          Positioned(
            left: 0,
            right: 0,
            top: 0,
            child: Container(
              height: 40,
              alignment: Alignment.center,
              color: makeStickyHeaderBgColor(shrinkOffset),
              child: Text(
                "过度头部",
                style: TextStyle(
                  fontSize: 20,
                  fontWeight: FontWeight.w500,
                  color: makeStickyHeaderTextColor(shrinkOffset, false), // 标题颜色
                ),
              ),
            ),
          )
        ],
      ),
    );
  }

  //SliverPersistentHeader最大高度
  @override
  double get maxExtent => 200;

  //SliverPersistentHeader最小高度
  @override
  double get minExtent => 40;

  @override
  bool shouldRebuild(
      covariant _SliverPersistentHeaderDelegateFloating oldDelegate) {
    return false;
  }

  Color makeStickyHeaderBgColor(shrinkOffset) {
    final int alpha =
        (shrinkOffset / (maxExtent - minExtent) * 255).clamp(0, 255).toInt();
    return Color.fromARGB(alpha, 255, 255, 255);
  }

  Color makeStickyHeaderTextColor(shrinkOffset, isIcon) {
    if (shrinkOffset <= 50) {
      return isIcon ? Colors.white : Colors.transparent;
    } else {
      final int alpha =
          (shrinkOffset / (maxExtent - minExtent) * 255).clamp(0, 255).toInt();
      return Color.fromARGB(alpha, 0, 0, 0);
    }
  }
}

class _SliverPersistentHeaderDelegate extends SliverPersistentHeaderDelegate {
  _SliverPersistentHeaderDelegate(this._tabBar);

  final TabBar _tabBar;

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return Container(
      color: Colors.green,
      child: _tabBar,
    );
  }

  //SliverPersistentHeader最大高度
  @override
  double get maxExtent => _tabBar.preferredSize.height;

  //SliverPersistentHeader最小高度
  @override
  double get minExtent => _tabBar.preferredSize.height;

  @override
  bool shouldRebuild(covariant _SliverPersistentHeaderDelegate oldDelegate) {
    return false;
  }
}
